package com.example.lib_base.widget

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.lib_base.R
import com.example.lib_base.utils.clickWithTrigger
import com.example.lib_base.widget.snap_recycleview.GravitySnapHelper


/**
 * 功能描述 分页
 * @param:
 * @return:
 * @autor: lds
 * @date:
 */
class PageViewLayout @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null,
    defStyleAttr: Int = 0
) :
    ConstraintLayout(context, attributeSet, defStyleAttr) {

    //上一页
    private var upImg: ImageView

    //下一页
    private var downImg: ImageView

    //分页信息
    private var pageInfo: TextView

    //当前页
    private var currentPage = 0

    //总页数
    private var totalPage = 0

    //总数据量
    private var totalCount = 0

    //类似接口
    private var editListener: ((Int) -> Unit)? = null
    private var currentListener: ((Int) -> Unit)? = null

    init {
        val mContentView = LayoutInflater.from(context).inflate(R.layout.page_view, this, false)
        upImg = mContentView.findViewById(R.id.up_image)
        downImg = mContentView.findViewById(R.id.down_image)
        pageInfo = mContentView.findViewById(R.id.edit)
        if (attributeSet != null) {
            val attrs = context.obtainStyledAttributes(attributeSet, R.styleable.PageViewLayout)
            for (index in 0 until attrs.indexCount) {
                when (attrs.getIndex(index)) {
                    R.styleable.PageViewLayout_upImage -> upImg.background =
                        attrs.getDrawable(
                            R.styleable.PageViewLayout_upImage
                        )

                    R.styleable.PageViewLayout_downImage ->
                        downImg.background =
                            attrs.getDrawable(R.styleable.PageViewLayout_downImage)
                    R.styleable.PageViewLayout_text_background -> pageInfo.background =
                        attrs.getDrawable(R.styleable.PageViewLayout_text_background)
                    R.styleable.PageViewLayout_currentPage -> currentPage =
                        attrs.getInteger(R.styleable.PageViewLayout_currentPage, 0)
                    R.styleable.PageViewLayout_totalPage -> totalCount =
                        attrs.getInteger(R.styleable.PageViewLayout_totalPage, 0)
                }
            }
            attrs.recycle()
        }
        pageInfo.text = context.getString(R.string.page_num, currentPage, totalPage)
        initView()
        addView(mContentView)
    }

    private fun initView() {
        initClickView()
        upImg.clickWithTrigger {
            currentPage--
            currentListener?.invoke(currentPage)
            initClickView()
        }
        downImg.clickWithTrigger {
            currentPage++
            currentListener?.invoke(currentPage)
            initClickView()
        }
        pageInfo.clickWithTrigger {
            editListener?.invoke(currentPage)
        }
    }

    private fun initClickView() {
        if (currentPage != 0 && totalPage != 0 && totalPage >= currentPage) {
            if (totalPage > currentPage) {
                if (currentPage > 1) {
                    isClickable(upImg, true)
                    isClickable(downImg, true)
                } else {
                    isClickable(upImg, false)
                    isClickable(downImg, true)
                }
            } else {
                if (currentPage == 1) {
                    isClickable(upImg, false)
                    isClickable(downImg, false)
                } else {
                    isClickable(upImg, true)
                    isClickable(downImg, false)
                }
            }
        } else {
            isClickable(upImg, false)
            isClickable(downImg, false)
        }
        pageInfo.text = context.getString(R.string.page_num, currentPage, totalPage)
    }

    //可点击与否
    private fun isClickable(view: View?, canClick: Boolean) {
        view?.let {
            if (canClick) {
                it.isEnabled = true
                it.alpha = 1f
            } else {
                it.isEnabled = false
                it.alpha = 0.3f
            }
        }
    }

    fun setPages(currentPage: Int, totalPage: Int) {
//        if (this.currentPage != currentPage && this.currentPage != 0){
//            currentListener?.invoke(currentPage)
//        }
        this.currentPage = currentPage
        this.totalPage = totalPage
        initClickView()
        invalidate()
    }

    /**
     * 编辑的点击
     */
    fun setEditListener(listener: ((Int) -> Unit)?) {
        this.editListener = listener
    }

    /**
     * 获取当前页的回调
     */
    private fun getUpDownCurrentPage(page: ((Int) -> Unit)) {
        this.currentListener = page
    }

    /**
     *  设置helper 和 PagingDataAdapter 进行自动分页和滑动分页
     */
    private var realTotalNum = 0 //实时adapter变化的数
    private var curPage = 0 //上下页的点击
    private var isClickPage = false //用于是滑动还是点击所变化的页数

    fun getTotalNum(): Int {
        return realTotalNum
    }

    fun getTotalPage(): Int {
        return totalPage
    }

    /**
     *  设置helper 和 PagingDataAdapter 进行自动分页和滑动分页
     *
     *   只需设置一次
     */
    fun setGravityHelperAndAdapter(
        helper: GravitySnapHelper?,
        adapter: PagingDataAdapter<*, *>?,
        limitPage: Int
    ) {
        if (helper != null) {
            getUpDownCurrentPage {
                curPage = if ((it * limitPage) <= realTotalNum) {
                    limitPage * (it - 1)
                } else {
                    realTotalNum - 1
                }
                helper.smoothScrollToPosition(curPage)
                isClickPage = true
            }
            if (helper.snapListener == null) {
                helper.setSnapListener {
                    totalPage = if (realTotalNum % limitPage != 0) {
                        realTotalNum / limitPage + 1
                    } else {
                        realTotalNum / limitPage
                    }
                    if (it >= 0 && totalPage != 0) {
                        if (isClickPage && curPage > it && (curPage / limitPage + 1) > (it / limitPage + 1)) {
                            setPages(curPage / limitPage + 1, totalPage)
                        } else {
                            setPages(it / limitPage + 1, totalPage)
                        }
                    } else {
                        setPages(0, totalPage)
                    }
                    isClickPage = false
                }
            }
            adapter?.addLoadStateListener {
                //新增数据滚动到最新数据位置
                if (adapter.itemCount - realTotalNum > 0 && adapter.itemCount > 0) {
                    realTotalNum = adapter.itemCount
                    helper.updateSnap(true, true, true)
                } else if (adapter.itemCount - realTotalNum < 0) {
                    realTotalNum = adapter.itemCount
                    helper.updateSnap(true, true, false)
                }
            }
        }
    }

    /**
     *  设置helper 和 RecyclerView.Adapter 进行自动分页和滑动分页
     *
     *  需要每次更新adapter item数目时
     */
    fun setGravityHelperAndAdapter(
        helper: GravitySnapHelper?,
        adapter: RecyclerView.Adapter<*>?,
        limitPage: Int
    ) {
        if (helper != null) {
            getUpDownCurrentPage {
                curPage = if ((it * limitPage) <= realTotalNum) {
                    limitPage * (it - 1)
                } else {
                    realTotalNum - 1
                }
                helper.smoothScrollToPosition(curPage)
                isClickPage = true
            }
            if (helper.snapListener == null) {
                helper.setSnapListener {
                    totalPage = if (realTotalNum % limitPage != 0) {
                        realTotalNum / limitPage + 1
                    } else {
                        realTotalNum / limitPage
                    }
                    Log.e("snapListener", "setGravityHelperAndAdapter: "+helper.currentSnappedPosition )
                    if (it >= 0 && totalPage != 0) {
                        if (isClickPage && curPage > it && (curPage / limitPage + 1) > (it / limitPage + 1)) {
                            setPages(curPage / limitPage + 1, totalPage)
                        } else {
                            if (helper.currentSnappedPosition != -1){
                                setPages(helper.currentSnappedPosition / limitPage + 1, totalPage)
                            }else {
                                setPages(it / limitPage + 1, totalPage)
                            }
                        }
                    } else {
                        setPages(0, totalPage)
                    }
                    isClickPage = false
                }
            }
            adapter?.let {
                //新增数据滚动到最新数据位置
                Log.e("setGravityHelperAndAdapter:", "${adapter.itemCount}" )
                if (adapter.itemCount - realTotalNum > 0 && adapter.itemCount > 0) {
                    realTotalNum = adapter.itemCount
                    helper.updateSnap(true, true, true)
                } else if (adapter.itemCount - realTotalNum < 0) {
                    realTotalNum = adapter.itemCount
                    helper.updateSnap(true, true, false)
                }
            }
        }
    }


}